package com.ihrm.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.Map;

@Getter
@Setter
@ConfigurationProperties("jwt.config")
public class JwtUtils {
    //签名私钥
    private String key;
    //签名失效时间
    private Long ttl;

    /**
     * 设置认证token
     *  id:登陆用户id
     *  subject:登陆用户名
     * @return
     */
    public String createJwt(String id,String name,Map<String,Object> map){
        //1，设置失效时间
        long now = System.currentTimeMillis();
        long exp = now + ttl;
        //2，创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);
        //3.根据map设置claims
        for(Map.Entry<String,Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }
        jwtBuilder.setExpiration(new Date(exp));
        //4，创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token字符串获取claims
     *
     */
    public Claims parseJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        System.out.println(claims.getId());
        return claims;
    }


    public static void main(String[] args) {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJjb21wYW55SWQiOiIxIiwiYXBpcyI6IiIsImNvbXBhbnlOYW1lIjoi5Lyg5pm65pKt5a6iIiwiZXhwIjoxNTk5NDgyMjI1fQ.mQ0G0JU55ZnnJj4MmEt4tS_J_Be7RJG5ZE9q5JF8C9A";
        Claims claims = Jwts.parser().setSigningKey("saas-ihrm").parseClaimsJws(token).getBody();
        System.out.println(claims.getId());
    }


}
